<template>
  <div class="topic-framework-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item>内容管理</el-breadcrumb-item>
            <el-breadcrumb-item>话题框架图</el-breadcrumb-item>
          </el-breadcrumb>
          <h1 class="page-title">
            <svg-icon icon-class="tree" style="margin-right: 10px; color: #1EB7E6;" />
            话题框架图
          </h1>
          <p class="page-description">
            以思维导图的形式管理话题层级结构，支持快速创建、编辑和组织话题关系
          </p>
        </div>
        <div class="header-right">
          <!-- Web网站选择器 -->
          <div class="header-controls">
            <el-select
              v-model="selectedWebId"
              placeholder="请选择目标网站"
              size="small"
              style="width: 200px; margin-right: 10px;"
              clearable
            >
              <el-option
                v-for="web in webList"
                :key="web.id"
                :label="web.domain"
                :value="web.id"
              >
                <span style="float: left">{{ web.domain }}</span>
                <span style="float: right; color: #8492a6; font-size: 12px">{{ web.name || web.domain }}</span>
              </el-option>
            </el-select>

            <!-- 快速操作 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              :disabled="!selectedWebId"
              @click="createQuickTopic"
            >
              快速创建话题
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 思维导图组件 -->
    <div class="mindmap-wrapper">
      <topic-mindmap ref="topicMindmap" :selected-web-id="selectedWebId" />
    </div>

    <!-- 快速创建话题对话框 -->
    <el-dialog
      title="快速创建话题"
      :visible.sync="quickCreateDialog.visible"
      width="40%"
    >
      <el-form ref="quickForm" :model="quickCreateDialog.form" :rules="quickCreateDialog.rules" label-width="80px">
        <el-form-item label="关键词" prop="keyword">
          <el-input
            v-model="quickCreateDialog.form.keyword"
            placeholder="输入话题关键词"
            @keyup.enter.native="quickCreateTopic"
          />
        </el-form-item>

        <el-form-item label="类型">
          <el-radio-group v-model="quickCreateDialog.form.type">
            <el-radio label="root">根话题</el-radio>
            <el-radio label="batch">批量创建</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="quickCreateDialog.form.type === 'batch'" label="批量输入">
          <el-input
            v-model="quickCreateDialog.form.batchKeywords"
            type="textarea"
            placeholder="每行一个关键词，将创建为同级话题"
            :rows="5"
          />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            提示：每行输入一个关键词，支持批量创建多个同级话题
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="quickCreateDialog.visible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="quickCreateDialog.creating"
          @click="quickCreateTopic"
        >
          创建
        </el-button>
      </div>
    </el-dialog>

    <!-- 统计信息面板 -->
    <div v-if="stats.visible" class="stats-panel">
      <el-card shadow="hover">
        <div slot="header" class="stats-header">
          <span>话题统计</span>
          <el-button
            type="text"
            icon="el-icon-close"
            @click="stats.visible = false"
          />
        </div>
        <div class="stats-content">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ stats.data.total || 0 }}</div>
                <div class="stat-label">总话题数</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ stats.data.completed || 0 }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ stats.data.inProgress || 0 }}</div>
                <div class="stat-label">进行中</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import TopicMindmap from '@/components/TopicMindmap'
import { createTopicNode } from '@/api/cms/topic_mindmap'
import { Get as getWebs } from '@/api/cms/web'

export default {
  name: 'TopicFrameworkPage',
  components: {
    TopicMindmap
  },

  data() {
    return {
      // Web网站管理
      webList: [],
      selectedWebId: null,

      // 快速创建对话框
      quickCreateDialog: {
        visible: false,
        creating: false,
        form: {
          keyword: '',
          type: 'root',
          batchKeywords: ''
        },
        rules: {
          keyword: [
            { required: true, message: '请输入关键词', trigger: 'blur' }
          ]
        }
      },

      // 统计信息
      stats: {
        visible: false,
        data: {
          total: 0,
          completed: 0,
          inProgress: 0
        }
      }
    }
  },

  mounted() {
    this.loadWebList()
    this.loadStats()
  },

  methods: {
    // 快速创建话题
    createQuickTopic() {
      if (!this.selectedWebId) {
        this.$message.warning('请先选择一个网站')
        return
      }
      this.quickCreateDialog.visible = true
      this.resetQuickForm()
    },

    // 执行快速创建
    async quickCreateTopic() {
      this.$refs.quickForm.validate(async(valid) => {
        if (!valid) return

        this.quickCreateDialog.creating = true

        try {
          if (this.quickCreateDialog.form.type === 'batch') {
            await this.createBatchTopics()
          } else {
            await this.createSingleTopic()
          }
        } catch (error) {
          console.error('创建话题错误:', error)
          this.$message.error('创建失败')
        } finally {
          this.quickCreateDialog.creating = false
        }
      })
    },

    // 创建单个话题
    async createSingleTopic() {
      if (!this.selectedWebId) {
        this.$message.warning('请先选择一个网站')
        return
      }

      const response = await createTopicNode({
        keyword: this.quickCreateDialog.form.keyword,
        title: this.quickCreateDialog.form.keyword,
        parent_id: null,
        web_id: this.selectedWebId
      })

      if (response.success) {
        this.$message.success('话题创建成功')
        this.quickCreateDialog.visible = false
        this.$refs.topicMindmap?.refreshMindmap()
        this.loadStats()
      } else {
        this.$message.error(response.msg || '创建失败')
      }
    },

    // 批量创建话题
    async createBatchTopics() {
      if (!this.selectedWebId) {
        this.$message.warning('请先选择一个网站')
        return
      }

      const keywords = this.quickCreateDialog.form.batchKeywords
        .split('\n')
        .map(line => line.trim())
        .filter(line => line.length > 0)

      if (keywords.length === 0) {
        this.$message.warning('请输入要创建的关键词')
        return
      }

      let successCount = 0
      let failedCount = 0

      for (const keyword of keywords) {
        try {
          const response = await createTopicNode({
            keyword: keyword,
            title: keyword,
            parent_id: null,
            web_id: this.selectedWebId
          })

          if (response.success) {
            successCount++
          } else {
            failedCount++
          }
        } catch (error) {
          failedCount++
        }
      }

      this.$message.success(`批量创建完成：成功 ${successCount} 个，失败 ${failedCount} 个`)
      this.quickCreateDialog.visible = false
      this.$refs.topicMindmap?.refreshMindmap()
      this.loadStats()
    },

    // 重置快速创建表单
    resetQuickForm() {
      this.quickCreateDialog.form = {
        keyword: '',
        type: 'root',
        batchKeywords: ''
      }

      this.$nextTick(() => {
        if (this.$refs.quickForm) {
          this.$refs.quickForm.clearValidate()
        }
      })
    },

    // 加载统计信息
    async loadStats() {
      // TODO: 实现统计信息加载
      // 这里应该调用后端API获取话题统计数据
      this.stats.data = {
        total: 0,
        completed: 0,
        inProgress: 0
      }
    },

    // 显示统计面板
    showStats() {
      this.stats.visible = true
      this.loadStats()
    },

    // 加载Web网站列表
    async loadWebList() {
      try {
        const response = await getWebs(null, 'page=1&pagesize=100')
        if (response.data && response.data.data) {
          this.webList = response.data.data
        }
      } catch (error) {
        console.error('加载Web列表失败:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.topic-framework-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;

  .page-header {
    background: white;
    border-bottom: 1px solid #e4e7ed;
    padding: 20px 30px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      max-width: 1400px;
      margin: 0 auto;

      .header-left {
        .page-title {
          font-size: 24px;
          color: #303133;
          margin: 10px 0;
          display: flex;
          align-items: center;
        }

        .page-description {
          color: #606266;
          margin: 0;
          line-height: 1.5;
        }
      }

      .header-right {
        margin-top: 10px;

        .header-controls {
          display: flex;
          align-items: center;
          gap: 10px;
        }
      }
    }
  }

  .mindmap-wrapper {
    flex: 1;
    overflow: hidden;
  }

  .stats-panel {
    position: fixed;
    top: 100px;
    right: 20px;
    width: 300px;
    z-index: 1000;

    .stats-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
    }

    .stats-content {
      .stat-item {
        text-align: center;

        .stat-number {
          font-size: 24px;
          font-weight: bold;
          color: #1EB7E6;
          margin-bottom: 5px;
        }

        .stat-label {
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }
}

::v-deep .el-breadcrumb {
  margin-bottom: 10px;

  .el-breadcrumb__inner {
    color: #909399;

    &.is-link {
      color: #1EB7E6;
    }
  }
}
</style>
